<?php
/**
 * User: Hufeng
 * Date: 2017/08/29 19:48
 * Desc: 用户Model
 */
namespace App\Model;
use SasPHP\SqlModel;

class TradeUserAssetModel extends SqlModel{
    protected $dbName = 'trade_user_asset';

    public function __construct(){
        parent::__construct('DB_SERVER');
    }

    function insertData($data){
        $this->dbConn->insert($this->dbName,$data);
        return $this->dbConn->id();
    }

    function editData($where,$data){
        $this->dbConn->update($this->dbName,$data,$where);
    }

    function delData($data){
        $this->dbConn->delete($this->dbName, $data);
    }

    function findData($where,$fields='*'){
        $res = $this->dbConn->get($this->dbName,$fields,$where);
        return $res;
    }

    function queryData($where,$fields='*'){
        $res = $this->dbConn->select($this->dbName,$fields,$where);
        return $res;
    }
    //获取统计数据
    public function getTotalNum($where){
        $res = $this->dbConn->count($this->dbName,$where);
        return $res;
    }
    //sum数据
    public function sumData($where,$param){
        $res = $this->dbConn->sum($this->dbName,$param,$where);
        return $res;
    }

    //增加更新用户持仓
    public function editUserHold($uid,$sid,$num,$price,$memo){
        if($num>0){
            $data = $this->findData(['uid'=>$uid,'sid'=>$sid]);
            if($data){
                $totalPrice = round(($price*$num)+($data['havenum']*$data['avg_price']),2);
                $totalNum = $num+$data['havenum'];
                $avgPrice = round($totalPrice/$totalNum,2);
                $this->editData(['id'=>$data['id']],['havenum'=>$totalNum,'avg_price'=>$avgPrice]);
            }else{
                $totalNum = $num;
                $this->insertData(['uid'=>$uid,'sid'=>$sid,'havenum'=>$num,'avg_price'=>$price]);
            }
            //记录用户股票变动明细
            $tualModel = new TradeUserAssetLogModel();
            $tualModel->insertData(['uid'=>$uid,'sid'=>$sid,'change_num'=>$num,'left_num'=>$totalNum,'status'=>1,'memo'=>$memo,'addtime'=>date('Y-m-d H:i:s')]);
        }
    }
    //委托交易
    public function dgTrade($uid,$sid,$num,$memo){
        $res = $this->findData(['uid'=>$uid,'sid'=>$sid]);
        if($res['havenum']<$num){
            return ['code'=>1,'msg'=>'持仓不足'];
        }
        //更新用户持仓
        $where = ['id'=>$res['id']];
        $eData = ['havenum[-]'=>$num];
        $this->editData($where,$eData);

        //记录用户股票变动明细
        $tualModel = new TradeUserAssetLogModel();
        $leftNum = $res['havenum'] - $num;
        $tualModel->insertData(['uid'=>$uid,'sid'=>$sid,'change_num'=>-$num,'left_num'=>$leftNum,'status'=>1,'memo'=>$memo,'addtime'=>date('Y-m-d H:i:s')]);
        return ['code'=>0,'holdAvgPrice'=>$res['avg_price']];
    }
}
